package com.labichaoka.chaoka.ui.splash;

import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;

import com.labichaoka.chaoka.R;
import com.labichaoka.chaoka.base.BaseActivity;
import com.labichaoka.chaoka.base.MyApplication;
import com.labichaoka.chaoka.entity.VersionCheckResponse;
import com.labichaoka.chaoka.ui.MainActivity;
import com.labichaoka.chaoka.utils.ThreadPoolManager;
import com.labichaoka.chaoka.utils.ToastUtils;
import com.labichaoka.chaoka.utils.UpdateManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

public class SplashActivity extends BaseActivity implements SplashView {

    private SplashPresenter presenter;

    @Override
    protected int initLayoutId() {
        return R.layout.activity_splash;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {
       presenter = new SplashPresenterImpl(this,new SplashInteractorImpl());
        try {
            int versionCode = MyApplication.getInstance().getPackageManager().getPackageInfo(MyApplication.mContext.getPackageName(), 0).versionCode;
            presenter.checkUpdate(versionCode + "");

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
//        presenter.getLocationData();//获取定位信息
//        presenter.getContactList();//获取通讯录
    }


    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }

    @Override
    public void update(VersionCheckResponse response) {
        VersionCheckResponse.Data data = response.getData();
        if (!TextUtils.isEmpty(data.getApkUrl())) {
            UpdateManager mUpdateManager = new UpdateManager(this,mContext, data.getApkUrl(), data.getDetail(), data.getCanSkip());
            mUpdateManager.checkUpdateInfo();
        }else{
            ToastUtils.show("获取数据异常!");
        }
    }

    @Override
    public void noUpdate() {
        goMain();
    }

    protected void onDestroy() {
        super.onDestroy();
        presenter.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void getEventBus(Integer num){
        if (num==1){
            goMain();
        }
    }

    public void  goMain(){
        ThreadPoolManager.getInstance().execute(() -> {
            try {
                Thread.sleep(500);
                gotoActivity(mContext,MainActivity.class,null);
                finish();

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }
}
